package com.fitzone.web.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fitzone.common.enums.BusinessType;
import com.fitzone.common.exception.LoginFailedException;
import com.fitzone.common.result.Result;
import com.fitzone.model.dto.CourseDTO;
import com.fitzone.model.dto.CoursePageDTO;
import com.fitzone.model.entity.*;
import com.fitzone.model.vo.CoachVO;
import com.fitzone.model.vo.CourseVO;
import com.fitzone.web.annotation.Log;
import com.fitzone.web.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@Api(tags = "课程管理")
@RequestMapping("/admin/course")
@RequiredArgsConstructor
public class CourseController {
    private final CourseService courseService;
    private final SysUserService sysUserService;
    private final StoreService storeService;
    private final CoachService coachService;

    @PostMapping
    @Log(title = "课程管理", businessType = BusinessType.INSERT)
    @ApiOperation("添加操作")
    public Result save(@RequestBody CourseDTO courseDTO){
        courseService.saveCourse(courseDTO);
        return Result.ok();
    }

    @PutMapping
    @Log(title = "课程管理", businessType = BusinessType.UPDATE)
    @ApiOperation("更新操作")
    public Result update(@RequestBody CourseDTO courseDTO){
        courseService.updateCourse(courseDTO);
        return Result.ok();
    }

    @DeleteMapping("/{id}")
//    @PreAuthorize("hasAuthority('bnt.store.list')")
    @ApiOperation("删除操作")
    public Result delete(@PathVariable Long id) {
        courseService.removeById(id);
        return Result.ok();
    }

    @GetMapping("/{page}/{limit}")
    @ApiOperation("查询操作")
    public Result<Page> page(CoursePageDTO coursePageDTO){
        Long principal = (Long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal == null){
            throw new LoginFailedException("账号错误");
        }

        SysUser user = sysUserService.getById(principal);

        Page<Course> pageInfo = new Page<>(coursePageDTO.getPage(), coursePageDTO.getLimit());
        Page<CourseVO> pageCourseInfo = new Page<>();
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(coursePageDTO.getCourseName() != null,Course::getCourseName, coursePageDTO.getCourseName())
                .orderByDesc(Course::getCreateTime)
                .eq(user.getStoreId() != null, Course::getStoreId,user.getStoreId());
        courseService.page(pageInfo,queryWrapper);

        BeanUtils.copyProperties(pageInfo, pageCourseInfo, "records");
        List<Course> records = pageInfo.getRecords();
        List<CourseVO> list = records.stream().map((item) -> {
            CourseVO courseVO = new CourseVO();
            BeanUtils.copyProperties(item, courseVO);
            Long coachId = item.getCoachId();
            Long storeId = item.getStoreId();
            Coach coach = coachService.getById(coachId);
            String coachName = coach.getCoachName();
            courseVO.setCoachName(coachName);
            Store store = storeService.getById(storeId);
            String storeName = store.getStoreName();
            courseVO.setStoreName(storeName);
            return courseVO;
        }).collect(Collectors.toList());
        pageCourseInfo.setRecords(list);
        return Result.ok(pageCourseInfo);
    }

    @ApiOperation(value = "根据id查询")
    @GetMapping("/{id}")
    public Result getId(@PathVariable Long id) {
        CourseVO course = courseService.getId(id);
        return Result.ok(course);
    }

    @Log(title = "教练管理", businessType = BusinessType.UPDATE)
    @GetMapping("/publishCourse/{id}")
    @ApiOperation("发布活动")
    public Result publishCourse(@PathVariable Long id) {
        courseService.publishCourse(id);
        return Result.ok();
    }
}
